package fti.uksw.ruang.fragment;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import fti.uksw.ruang.R;
import fti.uksw.ruang.dialog.DateTimeDialog;
import fti.uksw.ruang.dialog.MenuRepeatEventDialog;
import fti.uksw.ruang.model.CalendarEvent;
import fti.uksw.ruang.model.CalendarList;
import fti.uksw.ruang.model.Dosen;
import fti.uksw.ruang.model.Guest;
import fti.uksw.ruang.model.Login;
import fti.uksw.ruang.model.Pengguna;
import fti.uksw.ruang.model.RecurringDetail;

public class AddEventFragment extends Fragment {

	public static final String TAG = AddEventFragment.class.getName();

	private Spinner spinRoom;
	private Spinner spinDosen;
	private CheckBox cbAllDay;
	private Button btnStartHour;
	private Button btnEndHour;
	private Button btnStartDate;
	private Button btnEndDate;
	private TextView tvRepeat;
	private Spinner spinReminder;
	private EditText etTitle;
	private EditText etDesc;
	private EditText etPengguna;
	private EditText etNoHpPengguna;

	private AddEventFragmentListener mListener;

	private AdapterSpinnerCalendarList adapterCalList;
	private AdapterSpinnerDosen adapterDosen;
	private ArrayAdapter<CharSequence> adapterReminder;

	private CalendarList calList;
	private Dosen dosen;
	private Guest guest;
	private Pengguna pengguna;
	private CalendarEvent event;
	private Login login;
	private ArrayList<CalendarList> listCalList;
	private ArrayList<Dosen> listDosen;

	private Calendar calendarStart;
	private Calendar calendarStop;

	public interface AddEventFragmentListener {
		public void itemEvent(CalendarEvent mEvent);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
//		listCalList = getActivity().getIntent().getParcelableArrayListExtra(
//				CalendarList.TAG);
//		listDosen = getActivity().getIntent().getParcelableArrayListExtra(
//				Dosen.TAG);

//		Log.d(TAG, "Size calList : " + listCalList.size());
		
		login = (Login) getActivity().getIntent().getExtras().get(Login.TAG);
		

//		ActionBar ab = getActivity().getActionBar();
//		ab.setTitle("Add Schedule");

		event = new CalendarEvent();
		guest = new Guest();
		pengguna = new Pengguna();
	}

	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle SavedInstanceState) {

//		Log.d(TAG, "Size calList : " + listCalList.size());
		
		View v = inflater.inflate(R.layout.newevent, container, false);

		etTitle = (EditText) v.findViewById(R.id.et_newevent_title);
		etTitle.requestFocus();
		etTitle.setText("Untitle");
		event.setSubject(etTitle.getText().toString());
		
		spinRoom = (Spinner) v.findViewById(R.id.spin_newevent_room);
		btnStartHour = (Button) v.findViewById(R.id.btn_newevent_starthour);
		btnEndHour = (Button) v.findViewById(R.id.btn_newevent_endhour);
		btnStartDate = (Button) v.findViewById(R.id.btn_newevent_startDate);
		btnEndDate = (Button) v.findViewById(R.id.btn_newevent_enddate);
		cbAllDay = (CheckBox) v.findViewById(R.id.cb_newevent_allday);
		tvRepeat = (TextView) v.findViewById(R.id.tv_newevent_repeat);
		spinReminder = (Spinner) v.findViewById(R.id.spin_newevent_reminder);
		etDesc = (EditText) v.findViewById(R.id.et_newevent_description);
		
		etPengguna = (EditText) v.findViewById(R.id.et_newevent_pengguna);
		etPengguna.setText("Anonymous");
		etNoHpPengguna = (EditText) v.findViewById(R.id.et_newevent_telp);
		etNoHpPengguna.setText("-");
		pengguna.setNama(etPengguna.getText().toString());
		pengguna.setNoTelp(etNoHpPengguna.getText().toString());
		event.setPengguna(pengguna);
		
		spinDosen = (Spinner) v.findViewById(R.id.spin_newevent_dosen);

//		setRooms(v);
//		setDosen(v);
		setDateTime();
		setReminder(v);

		etTitle.addTextChangedListener(etTitleTextWatcher);
		etPengguna.addTextChangedListener(etPenggunaTextWatcher);
		etNoHpPengguna.addTextChangedListener(etNoHpPenggunaTextWatcher);
		spinRoom.setOnItemSelectedListener(spinRoomSelectedeItemListener);
		spinDosen.setOnItemSelectedListener(spinDosenSelectedItemListener);
		btnStartDate.setOnClickListener(setDateListener);
		btnEndDate.setOnClickListener(setDateListener);
		btnStartHour.setOnClickListener(setDateListener);
		btnEndHour.setOnClickListener(setDateListener);
		cbAllDay.setOnCheckedChangeListener(cbAllDayCheckedListener);
		tvRepeat.setOnClickListener(tvRepeatClickListener);
		spinReminder
				.setOnItemSelectedListener(spinReminderSelectedItemListener);
		etDesc.addTextChangedListener(etDescTextWatcher);

		init();
		
		return v;
	}

	private void init(){
		event.setEventId("offline");
		event.setColor("");
		event.setDescription(etDesc.getText().toString());
		event.setEndTime(calendarStop.getTime());
		event.setIsAllDayEvent(CalendarEvent.UNFLAG);
		event.setLocation("-");
		event.setOperatorId(login.getId());
		event.setRecurringRule(CalendarEvent.UNFLAG);
		event.setRecurringDetail(null);
		event.setStartTime(calendarStart.getTime());
		event.setGuest(guest);
		event.setPengguna(pengguna);
		mListener.itemEvent(event);
	}
	
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		try {
			mListener = (AddEventFragmentListener) activity;
		} catch (ClassCastException cce) {
			throw new ClassCastException(activity.toString()
					+ " must implement AddEventFragmentListener");
		}
	}
	
	private TextWatcher etNoHpPenggunaTextWatcher = new TextWatcher() {
		
		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
		}
		
		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
		}
		
		@Override
		public void afterTextChanged(Editable s) {
			pengguna.setNoTelp(etNoHpPengguna.getText().toString());
			event.setPengguna(pengguna);
		}
	};
	
	private TextWatcher etPenggunaTextWatcher = new TextWatcher() {
		
		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
		}
		
		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
		}
		
		@Override
		public void afterTextChanged(Editable s) {
			pengguna.setNama(etPengguna.getText().toString());
			event.setPengguna(pengguna);
		}
	};

	private TextWatcher etDescTextWatcher = new TextWatcher() {

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
		}

		@Override
		public void afterTextChanged(Editable s) {
			event.setDescription(etDesc.getText().toString());
			mListener.itemEvent(event);
		}
	};

	private TextWatcher etTitleTextWatcher = new TextWatcher() {

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
		}

		@Override
		public void afterTextChanged(Editable s) {
			event.setSubject(etTitle.getText().toString());		
		}
	};

	private void setDateTime() {
		calendarStart = Calendar.getInstance(Locale.getDefault());
		btnStartDate.setText(sdfDate.format(calendarStart.getTime()));
		btnStartHour.setText(sdfTime.format(calendarStart.getTime()));

		calendarStop = Calendar.getInstance(Locale.getDefault());
		calendarStop.add(Calendar.HOUR_OF_DAY, 2);
		btnEndDate.setText(sdfDate.format(calendarStop.getTime()));
		// calendarStop.set(Calendar.HOUR_OF_DAY,
		// calendarStop.get(Calendar.HOUR_OF_DAY));
		btnEndHour.setText(sdfTime.format(calendarStop.getTime()));
	}

	public void setRooms(ArrayList<CalendarList> calList) {
		adapterCalList = new AdapterSpinnerCalendarList(calList);
		spinRoom.setAdapter(adapterCalList);
	}

	public void setDosen(ArrayList<Dosen> dosenList) {
		adapterDosen = new AdapterSpinnerDosen(dosenList);
		spinDosen.setAdapter(adapterDosen);
	}

	private void setReminder(View v) {
		adapterReminder = ArrayAdapter.createFromResource(v.getContext(),
				R.array.menureminder, android.R.layout.simple_spinner_item);
		adapterReminder
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinReminder.setAdapter(adapterReminder);
	}

	private AdapterView.OnItemSelectedListener spinDosenSelectedItemListener = new AdapterView.OnItemSelectedListener() {

		@Override
		public void onItemSelected(AdapterView<?> adapter, View view, int pos,
				long arg3) {
			if (view != null) {
				dosen = (Dosen) adapter.getItemAtPosition(pos);
				guest = new Guest();
				guest.setIdDosen(dosen.getId());
				event.setGuest(guest);
				mListener.itemEvent(event);
			}
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
		}
	};

	private AdapterView.OnItemSelectedListener spinReminderSelectedItemListener = new AdapterView.OnItemSelectedListener() {

		@Override
		public void onItemSelected(AdapterView<?> adapter, View view, int pos,
				long id) {
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
		}
		//
	};

	private AdapterView.OnItemSelectedListener spinRoomSelectedeItemListener = new AdapterView.OnItemSelectedListener() {

		@Override
		public void onItemSelected(AdapterView<?> adapter, View view, int pos,
				long id) {
			if (view != null) {
				calList = (CalendarList) adapter.getItemAtPosition(pos);
				event.setCalendarId(calList.getCalendarId());
				mListener.itemEvent(event);
			}
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
		}
	};

	private OnClickListener tvRepeatClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			MenuRepeatEventDialog mred = MenuRepeatEventDialog.newInstance(
					v.getContext(), event.getEndTime().getTime());
			mred.setMenuRepeatEventDialogListener(new MenuRepeatEventDialog.MenuRepeatEventDialogListener() {

				@Override
				public void MenuItemSelected(String item) {
				}

				@Override
				public void ItemSelected(String item) {
					String[] repeatStr = item.split("-");
					if (repeatStr[0].equals(RecurringDetail.MODE_NOREPEAT)) {
						event.setRecurringRule(CalendarEvent.UNFLAG);
					} else {
						event.setRecurringRule(CalendarEvent.FLAG);
						RecurringDetail _rd = new RecurringDetail();
						_rd.setInterval(1);
						_rd.setType(repeatStr[0]);
						_rd.setUntil(new Date(Long.valueOf(repeatStr[2])));

						event.setRecurringDetail(_rd);

						tvRepeat.setText(getResources().getString(
								R.string.newevent_repeat)
								+ "\n" + repeatStr[0] + " " + repeatStr[1]);
					}
					mListener.itemEvent(event);

				}
			});
			mred.show(getFragmentManager(), "menu repeat");
		}
	};

	private OnClickListener setDateListener = new OnClickListener() {

		@Override
		public void onClick(final View v) {
			// Calendar c = Calendar.getInstance();
			DateTimeDialog dtd = null;
			if (v == btnStartDate) {
				dtd = DateTimeDialog.newInstance(v.getContext(),
						DateTimeDialog.DATEDIALOG, calendarStart);
			} else if (v == btnEndDate) {
				dtd = DateTimeDialog.newInstance(v.getContext(),
						DateTimeDialog.DATEDIALOG, calendarStop);
			} else if (v == btnStartHour) {
				dtd = DateTimeDialog.newInstance(v.getContext(),
						DateTimeDialog.TIMEDIALOG, calendarStart);
			} else if (v == btnEndHour) {
				dtd = DateTimeDialog.newInstance(v.getContext(),
						DateTimeDialog.TIMEDIALOG, calendarStop);
			}
			dtd.setDateTimeDialogFragmentListener(new DateTimeDialog.DateTimeDialogFragmentListener() {

				@Override
				public void dateDialogFragmentDateTimeSet(Calendar calendar) {
					if (v == btnStartDate)
						setStartDate(calendar);
					else if (v == btnEndDate)
						setEndDate(calendar);
					else if (v == btnStartHour)
						setStartHour(calendar);
					else if (v == btnEndHour) {
						setEndHour(calendar);
					}
				}
			});
			dtd.show(getFragmentManager(), "date picker dialog fragment");

		}
	};

	private OnCheckedChangeListener cbAllDayCheckedListener = new OnCheckedChangeListener() {

		@Override
		public void onCheckedChanged(CompoundButton buttonView,
				boolean isChecked) {
			if (isChecked) {
				btnStartHour.setVisibility(View.INVISIBLE);
				btnEndHour.setVisibility(View.INVISIBLE);
				event.setIsAllDayEvent(CalendarEvent.FLAG);
			} else {
				btnStartHour.setVisibility(View.VISIBLE);
				btnEndHour.setVisibility(View.VISIBLE);
				event.setIsAllDayEvent(CalendarEvent.UNFLAG);
			}
		}
	};

	SimpleDateFormat sdfDate = new SimpleDateFormat("EE, MMM dd, yyyy",
			Locale.getDefault());
	SimpleDateFormat sdfTime = new SimpleDateFormat("h:mm a",
			Locale.getDefault());

	public void setStartHour(Calendar c) {
		btnStartHour.setText(sdfTime.format(c.getTime()));
		calendarStart.set(Calendar.HOUR_OF_DAY, c.get(Calendar.HOUR_OF_DAY));
		calendarStart.set(Calendar.MINUTE, c.get(Calendar.MINUTE));
		event.setStartTime(calendarStart.getTime());
		mListener.itemEvent(event);
	}

	public void setEndHour(Calendar c) {
		btnEndHour.setText(sdfTime.format(c.getTime()));
		calendarStop.set(Calendar.HOUR_OF_DAY, c.get(Calendar.HOUR_OF_DAY));
		calendarStop.set(Calendar.MINUTE, c.get(Calendar.MINUTE));
		event.setEndTime(calendarStop.getTime());
		mListener.itemEvent(event);
	}

	public void setStartDate(Calendar c) {
		btnStartDate.setText(sdfDate.format(c.getTime()));
		calendarStart.set(Calendar.DAY_OF_MONTH, c.get(Calendar.DAY_OF_MONTH));
		calendarStart.set(Calendar.MONTH, c.get(Calendar.MONTH));
		calendarStart.set(Calendar.YEAR, c.get(Calendar.YEAR));
		event.setStartTime(calendarStart.getTime());
		mListener.itemEvent(event);
	}

	public void setEndDate(Calendar c) {
		btnEndDate.setText(sdfDate.format(c.getTime()));
		calendarStop.set(Calendar.DAY_OF_MONTH, c.get(Calendar.DAY_OF_MONTH));
		calendarStop.set(Calendar.MONTH, c.get(Calendar.MONTH));
		calendarStop.set(Calendar.YEAR, c.get(Calendar.YEAR));
		event.setEndTime(calendarStop.getTime());
		mListener.itemEvent(event);
	}

	public class AdapterSpinnerDosen extends BaseAdapter implements
			SpinnerAdapter {

		private List<Dosen> list;

		public AdapterSpinnerDosen(List<Dosen> mList) {
			list = mList;
		}

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Dosen getItem(int arg0) {
			return list.get(arg0);
		}

		@Override
		public long getItemId(int position) {
			return list.get(position).getId();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			TextView tv;
			if (convertView != null) {
				tv = (TextView) convertView;
			} else {
				tv = (TextView) getActivity().getLayoutInflater().inflate(
						android.R.layout.simple_dropdown_item_1line, parent,
						false);
			}
			tv.setPadding(0, 0, 0, 0);
			tv.setTextColor(Color.BLACK);
			tv.setText(list.get(position).getNama());

			return tv;
		}

	}

	public class AdapterSpinnerCalendarList extends BaseAdapter implements
			SpinnerAdapter {

		private List<CalendarList> list;

		public AdapterSpinnerCalendarList(List<CalendarList> mList) {
			list = mList;
		}

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public CalendarList getItem(int arg0) {
			return list.get(arg0);
		}

		@Override
		public long getItemId(int position) {
			return list.get(position).getId();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			TextView tv;
			if (convertView != null) {
				tv = (TextView) convertView;
			} else {
				tv = (TextView) getActivity().getLayoutInflater().inflate(
						android.R.layout.simple_dropdown_item_1line, parent,
						false);
			}
			tv.setPadding(0, 0, 0, 0);
			tv.setTextColor(Color.BLACK);
			tv.setText(list.get(position).getCalendarTitle());

			return tv;
		}

	}
}
